<?php

namespace App\Http\Controllers;

use App\Format\UserFormat;
use App\Http\Requests\UserChangeRequest;
use App\Services\SmsService;
use App\Services\UserService;
use Illuminate\Http\Request;

class UserController extends Controller
{
    protected $userService;

    public function __construct(Request $request, UserService $userService)
    {
        $this->userService = $userService;
        parent::__construct($request);
    }

    public function getVcode(Request $request)
    {
        $vcode = $this->userService->getVcodeForLogin($request->input('phone'));
        return renderSuccessJson(['vcode' => $vcode]);
    }

    public function login(Request $request)
    {
        $login = $this->userService->login($request->input('phone'), $request->input('hashPwd'));
        return renderSuccessJson($login);
    }

    public function sendRegSms(Request $request, SmsService $smsService)
    {
        $smsService->sendCode($request->input('phone'), rand(0000, 9999), 'REG');
        return renderSuccessJson();
    }

    public function reg(Request $request)
    {
        $login = $this->userService->reg(
            $request->input('phone'),
            $request->input('code'),
            $request->input('userName'),
            $request->input('password'),
        );

        return renderSuccessJson($login);
    }

    public function userCenter()
    {
        return renderSuccessJson($this->userService->profile($this->userId));
    }

    public function getUserReadLog()
    {
        $log = $this->userService->getUserReadLog($this->userId);
        return renderSuccessJson($log);
    }

    public function getUserConsumptionLog()
    {
        $log = $this->userService->getUserConsumptionLog($this->userId, $this->requests['page'] ?? 1);
        return renderSuccessJson($log);
    }

    public function changeUser(UserChangeRequest $userChangeRequest)
    {
        $userFormat = new UserFormat($userChangeRequest->all());
        $this->userService->changeUser($this->userId, $userFormat);
        return renderSuccessJson();
    }

    public function logout()
    {
        $this->userService->logout($this->userId);
        return renderSuccessJson();
    }

    public function devUserCoupon(Request $request)
    {
        $phone = $request->input('phone');
        $key = $request->input('key');
        if ($key != $_SERVER['dev_key']) {
            return renderSuccessJson(['msg' => '呸']);
        }
        $this->userService->sendDevUserCoupon($phone);
        return renderSuccessJson();
    }
}
